package ac.rsync.test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

// java 实现文件 复制 拷贝 下载
public class FileCopy
{
	public static int buffer_size = 2048;

	private void doCopyByPath(String sourceFile, String destFile) throws IOException
	{

		File src = new File(sourceFile);
		File dst = new File(destFile);
		if (!dst.exists())
		{// 目标文件对应的目录不存在，创建新的目录
			int index = new String(destFile).lastIndexOf("/");
			String path = destFile.substring(0, index);
			new File(path).mkdirs();
		}
		doCopy(src, dst);
	}

	private static void doCopy(File src, File dst)
	{
		if (src.isFile())
		{
			try
			{
				copyFile(src, dst);

			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		else
		{
			File dir = copyDirectory(src, dst);
			File[] files = src.listFiles();
			if (files.length == 0)
			{

			}
			else
			{
				for (File file : files)
				{
					doCopy(file, dir);
				}
			}
		}
	}

	public static void copy(File src, File dst) throws IOException
	{
		if (!src.exists() || !dst.exists())
			throw new FileNotFoundException();
		else if (src.isFile() && dst.isFile())
			copy(new FileReader(src), new FileWriter(dst));
		else if (src.isDirectory() && (!dst.isDirectory()))
			throw new IllegalArgumentException("Destination should be a directory!");
		else
		{
			doCopy(src, dst);
		}

	}

	private static void copyFile(File src, File dst) throws IOException
	{
		File file = new File(dst, src.getName());
		copy(new FileReader(src), new FileWriter(file));
	}

	private static File copyDirectory(File src, File dst)
	{
		File file = new File(dst, src.getName());
		file.mkdir();
		return file;
	}

	private static int copy(Reader in, Writer out) throws IOException
	{
		int byteCount = 0;
		try
		{
			int bytesReader = -1;
			char[] buffer = new char[buffer_size];

			while((bytesReader = in.read(buffer)) != -1)
			{
				out.write(buffer, 0, bytesReader);
				byteCount += bytesReader;
			}
			out.flush();
		}
		finally
		{
			in.close();
			out.close();
		}
		return byteCount;
	}

	public static void main(String[] args) throws IOException
	{

		FileCopy c = new FileCopy();

		String sourceFile = "D:/fileTest/a/test.txt";
		String destFile = "D:/fileTest/c";
		c.doCopyByPath(sourceFile, destFile);

		// copy file
		String sourceFile1 = "D:/fileTest/a";
		String destFile1 = "D:/fileTest/aa";
		c.doCopyByPath(sourceFile1, destFile1);
		
	}
}
